package com.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seckill.service.ISeckillGoodsService;
import com.seckill.utils.MD5Util;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;
import com.seckill.exception.GlobalException;
import com.seckill.mapper.GoodsMapper;
import com.seckill.mapper.OrderMapper;
import com.seckill.mapper.SeckillGoodsMapper;
import com.seckill.mapper.SeckillOrderMapper;
import com.seckill.pojo.Orders;
import com.seckill.pojo.SeckillGoods;
import com.seckill.pojo.SeckillOrder;
import com.seckill.pojo.User;
import com.seckill.service.IOrderService;
import com.seckill.utils.UUIDUtil;
import com.seckill.vo.GoodsVo;
import com.seckill.vo.OrderDetailVo;
import com.seckill.vo.RespBeanEnum;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author levi
 * @since 2021-08-26
 */
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements IOrderService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId == null) {
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        Orders orders = orderMapper.selectById(orderId);
        GoodsVo goods = goodsMapper.findGoodsVoByGoodsId(orders.getGoodsId());
        OrderDetailVo orderDetailVo = new OrderDetailVo(goods, orders);
        return orderDetailVo;
    }

    @Transactional
    @Override
    public Orders seckill(User user, GoodsVo goods) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        // 库存减一 seckill_goods
        SeckillGoods seckillGoods = seckillGoodsMapper.selectOne(
                new QueryWrapper<SeckillGoods>().eq("goods_id", goods.getId()));

        //多个线程进入，回到值库存超卖，我们应该更改减库存的方式，采用sql语句判断库存余额，有库存才减
        /*seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        seckillGoodsMapper.updateById(seckillGoods);*/

        //这句有问题，多线程下会有多个线程同时在这里
        /*seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        int result = seckillGoodsMapper.update(seckillGoods, new UpdateWrapper<SeckillGoods>()
                .eq("id", goods.getId())
                .gt("stock_count", 0));
        */
        int result = seckillGoodsMapper.update(null, new UpdateWrapper<SeckillGoods>()
                .setSql("stock_count = stock_count - 1")
                .eq("id", goods.getId())
                .gt("stock_count", 0));
        if (result <= 0) {
            // 没有减库存，即库存不足，我们就直接返回null，不再生成订单
            valueOperations.set("isStockEmpty:" + goods.getId(), "0");
            log.info("更新不成功,不再生成订单{}", seckillGoods.getStockCount());
            return null;
        }

        // 生成订单  orders
        Orders orders = new Orders();
        orders.setUserId(user.getId());
        orders.setGoodsId(goods.getId());
        orders.setDeliveryAddrId(0L);
        orders.setGoodsName(goods.getGoodsName());
        orders.setGoodsCount(1);
        orders.setGoodsPrice(seckillGoods.getSeckillPrice());
        orders.setOrderChannel(1);
        orders.setStatus(0);// 创建未支付
        orders.setCreateDate(new Date());
        orderMapper.insert(orders);
        // 生成秒杀订单 seckill_order
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(orders.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrderMapper.insert(seckillOrder);
        // 解决同一用户同时秒杀多件商品：使用user_id+goods_id建立唯一索引接口，优化：再将秒杀订单信息存入redis
        redisTemplate.opsForValue().set("orders:" + user.getId() + ":" + goods.getId(), seckillOrder);
        return orders;
    }

    /**
     * 获取秒杀结果
     *
     * @param user
     * @return orderId 成功>0 等待=0 失败<0
     */
    @Override
    public Long getResult(User user, Long goodsId) {
        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new QueryWrapper<SeckillOrder>()
                .eq("user_id", user.getId())
                .eq("goods_id", goodsId));
        if (seckillOrder != null) {
            return seckillOrder.getId();
        } else {
            if (redisTemplate.hasKey("isStockEmpty:" + goodsId)) {
                return -1L;
            } else {
                return 0L;
            }
        }
    }

    @Override
    public String createPath(User user, Long goodsId) {
        String path = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisTemplate.opsForValue().set("seckillpath:" + user.getId() + ":" + goodsId, path, 60, TimeUnit.SECONDS);
        return path;
    }

    @Override
    public boolean checkPath(User user, Long goodsId, String path) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(path)) {
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("seckillpath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }

    @Override
    public boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(captcha)) {
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        return captcha.equals(redisCaptcha);
    }
}
